function MinePublishJobController(analyseId){
	
	this.jobDialog = null;
	this.flowsParam = {};
	flowInfo = {};
	var paramLabel = TempoUtils.locale("mine.publish-mine-job-param-label");
	
	// 当手动调度任务时，持续到列表刷新出来都想要的结果
	// 当停止任务时，持续到任务结束或者失败
	var DataObserveCenter = (function() {
		var manualArray = {};
		var stopArray = {};
		return {
			manualJob: function(id) {
				manualArray[id] = true;
			},
			isObserve: function(id) {
				return !!manualArray[id];
			},
			remove: function(id) {
				if(manualArray[id]) delete manualArray[id];
				if(stopArray[id]) delete stopArray[id];
			},
			isStop: function(id) {
				return !!stopArray[id];
			},
			stopJob: function(id) {
				stopArray[id] = true;
			}
		}
	})();
	
	/**
	 * 运行任务
	 */
	var runJob = function(job){
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/runJob',
			type : 'post',
			data : {id : job.id, triggerId : job.jobId},
			success : function(obj) {
				if (obj) {
					console.log(obj);
				}
			}
		});
	}
	/**
	 * 停止任务
	 */
	var stopJob = function(job, callback){
		DataObserveCenter.stopJob(job.id);
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/stopJob',
			type : 'post',
			data : {id : job.id, triggerId : job.jobId},
			success : function(obj) {
				if (obj) {
					$("<div/>").alert({msg :  TempoUtils.locale("mine.publish-job-killed"), height : 180});
				}else{
					$("<div/>").alert({msg :  TempoUtils.locale("mine.publish-job-notexists"), height : 180});
				}
				if(callback) callback();
			}
		});
	}
	/**
	 * 暂停任务
	 */
	var pauseJob = function(job){
		var url = contextPath + '/api/ai/mine/publish/pauseJob';
		if(job.trigger.status == 'PAUSED'){
			url = contextPath + '/api/ai/mine/publish/restartJob'
		} else if (job.trigger.status == 'COMPLETE') {
			$("<div/>").alert({msg :  TempoUtils.locale("mine.renwuyijingwancheng"), height : 180});
			return false;
		}
		$.ajax({
			url : url,
			type : 'post',
			data : {id : job.id, triggerId : job.jobId},
			success : function(obj) {
				if(job.status != 'PAUSED'){
					if(obj && obj != '0'){
						$("<div/>").alert({msg :  TempoUtils.locale("mine.renwuyijingyunxing"), height : 180});
					}
				}
				$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
			}
		});
	}
	/**
	 * 手动执行
	 */
	var manualJob = function(job){
		$.ajax({
			url : contextPath + "/api/ai/mine/publish/manualJob",
			type : 'post',
			data : {id : job.id, triggerId : job.jobId},
			success : function(obj) {
				if(obj) {
					DataObserveCenter.manualJob(job.id);
					$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
				} else {
					$("<div/>").alert({msg :  TempoUtils.locale("mine.renwuzhixingzhong"), height : 180});
				}
			}
		});
	}
	
	var deleteJob = function(job){
		var jobId = job.jobId;
		$("<div/>").confirm({
			title :  TempoUtils.locale("mine.publish-btn-delete"), 
			msg :  TempoUtils.locale("mine.publish-mine-job-grid-col-delete-confirm"),
			height : 160,
			width : 220,
			ok : function(){
				var process = $("<div/>").tempoprogressbar();
				$.ajax({
					url : contextPath + '/api/ai/mine/publish/deleteJob',
					type : 'post',
					data : {triggerId : jobId, id : job.id},
					success : function(obj) {
						process.tempoprogressbar("destroy");
						$(".tempo-ui-icon-refresh").trigger("click");
						$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
					}
				});
			}
		});
	}
	
	var editJob = function(job){
		var that = this;
		newJob.apply(that, [job,true]);
	}
	
	/**
	 * 新增调度
	 */
	var newJob = function(job, isEdit){
		var that = this;
		that.flowsParam = {}; 
		that.jobDialog = $('#tempo-mine-flow-job-dialog').clone().appendTo('body');
		that.jobDialog.dialog({
			width : 680,
			height: 520,
			autoOpen : false,
			title: TempoUtils.locale('mine.publish-mine-job-dialog-title'),
			modal:true,
			resizable: false,
			close:function(){
				that.jobDialog.dialog("destroy");
			},
			buttons:[{
				text: TempoUtils.locale('mine.publish-dialog-sure'),
				click:function(){
					saveJobConfig.apply(that, [job, isEdit]);
				}
			},{
				text:TempoUtils.locale('mine.publish-dialog-cancel'),
				click:function(){
					that.jobDialog.dialog("close");
				}
			}]
		});
		that.jobDialog.dialog('open');
		initJobLayout.apply(that, isEdit ? [job] : null);

	}
	
	/**
	 * 初始化表单数据
	 */
	var initFormData = function(job){
		var that = this;
		var dialog = that.jobDialog;
		job = job || {};
		TempoUtils.parserUi(dialog, job);
		
		dialog.find('input[name="retry"]').checkbox({
			change: function(e, ui) {
				console.log(e, ui);
				if(ui.checked) {
					dialog.find('input[name="retryNum"]').numberbox({disabled: false, required: true});
				} else {
					dialog.find('input[name="retryNum"]').numberbox({disabled: true, required: false});
				}
			}
		});
		
		dialog.find('.datefield').datepicker({
			dateFormat: 'yy-mm-dd',
			onClose : function(){
				if($(this).val()){
					$(this).validatebox('response', $(this).val());
				}
			},
			onSelect :function(){
				
			},
			onChangeMonthYear : function(year, month, inst){ 
				var month = inst.selectedMonth + 1;
				var day = inst.selectedDay;
				var format = function(v) { return String(v).length > 1 ? v : ('0' + v) }
				$(this).val(inst.selectedYear + '-' + format(month) + '-' + format(inst.selectedDay));
				$.datepicker._hideDatepicker(this);
			}
		});
		dialog.find('.timefield').timepicker({
			onClose : function(){
				if($(this).val()){
					$(this).validatebox('response', $(this).val());
				}
			},
			onSelect :function(){
				
			},
			timeInput : true
		});
		
		var internalInput = dialog.find('input[name=interval]');
		dialog.find('select[name="triggertype"]').selectmenu({
			selectFirst: false,
			change: function(e, ui) {
				console.log(e, ui);
				changeTriggerType(ui.item.value);
			}
		});
		
		var changeTriggerType = function(value) {
			if(value == "-2") {
				//分钟
				switchShowItem(dialog, false, true, false, true, 1);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-minute"));
				internalInput.numberbox({max: 59, min: 1}).val(30);
			} else if(value == "-1") {
				//小时
				switchShowItem(dialog, false, true, false, true, 1);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-hour"));
				internalInput.numberbox({max: 23, min: 1}).val(3);
			} else if(value == "0") {
				//天
				switchShowItem(dialog, false, false, true, true, 3);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-day"));
				internalInput.numberbox({max: 31, min: 1}).val(1);
			} else if(value == "1") {
				//周
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-week"));
				switchShowItem(dialog, true, false, true, false);
				buildWeeks(dialog);
				internalInput.numberbox({max: 6, min: 1}).val(1);
			} else if(value == "2") {
				//月
				switchShowItem(dialog, true, false, true, true, 2);
				dialog.find('.internal-unit').text(TempoUtils.locale("mine.publish-mine-job-triggertype-month"));
				buildDays(dialog);
				internalInput.numberbox({max: 11, min: 1}).val(1);
			}
		}
		
		//调度名称
		if(!$.isEmptyObject(job)){
			dialog.find('input[name="starttime"]').val(job.trigger.starttime);
			dialog.find('input[name="endtime"]').val(job.trigger.endtime);
			dialog.find('input[name="stime"]').val(job.trigger.stime);
			dialog.find('input[name="etime"]').val(job.trigger.etime);
			dialog.find('select[name="priority"]').val(job.trigger.priority).selectmenu('refresh');
			dialog.find('input[name="id"]').val(job.id);
			dialog.find('input[name="name"]').val(job.trigger.name);
			dialog.find('select[name="triggertype"]').val(job.trigger.triggertype).selectmenu('refresh');
			changeTriggerType(job.trigger.triggertype);
			internalInput.val(job.trigger.interval);
			if(job.trigger.rundate) {
				var days = job.trigger.rundate.split(",");
				if(job.trigger.triggertype == '1') {
					dialog.find('input[name=dayofweek]').each(function() {
						var $this = $(this);
						if(days.indexOf($this.val()) > -1) {
							$this.checkbox('check', $this.val());
						}
					});
				} else if(job.trigger.triggertype == '2') {
					dialog.find('input[name=dayofmonth]').each(function() {
						var $this = $(this);
						if(days.indexOf($this.val()) > -1) {
							$this.checkbox('check', $this.val());
						}
					});
				}
			}
			if(job.trigger.runType) {
				dialog.find('input[name=runType]').radio('check', job.trigger.runType);
			}
			if((job.trigger.triggertype == '-2' || job.trigger.triggertype == '-1')
					&& job.trigger.runType != 'inner-day' && job.trigger.runType != 'outer-day') {
				dialog.find('input[name=runType]').radio('check', 'inner-day');
			}
			if(job.trigger.retry) {
				dialog.find('input[name=retry]').click();
				dialog.find('input[name=retryNum]').numberbox({disabled: false, required: true, value: job.trigger.retryNum});
			}
		} else {
			dialog.find('select[name="triggertype"]').val(0).selectmenu('refresh');
			changeTriggerType(0);
			dialog.find('input[name=starttime]').val(DateUtils.formatDate(new Date()));
		}
	}
	
	var switchShowItem = function(dialog, timesRow, timeRange, dayTime, interval, dayMonthYear) {
		var _onoff = $.fn.onoff;
		$.fn.onoff = function(value) {
			var element = $(this);
			if(value) {
				element.show();
			} else {
				element.hide();
			}
			element.find('input').each(function(index, ele) {
				var role = $(ele).attr('ui-role');
				if(role == 'validatebox' || role == 'numberbox') {
					!value ? $(ele)[role]('disable') : $(ele)[role]('enable');
				}
			});
		}
		/////////////////////////////////////////////
		dialog.find('.times-row').onoff(timesRow);
		dialog.find('.times-board').empty();
		if(timeRange) {
			dialog.find('.day-of-time-range-row input[name=stime]')
				.validatebox({required: true}).validatebox('validate');
		} else {
			dialog.find('.day-of-time-range-row input[name=stime]')
				.validatebox({required: false}).validatebox('validate');
		}
		dialog.find('.day-of-time-range-row').onoff(timeRange);
		dialog.find('.day-of-time-row').onoff(dayTime);
		dialog.find('.time-interval-row').onoff(interval);
		if(interval && dayMonthYear != undefined) {
			dialog.find('.time-of-day').onoff(dayMonthYear == 1);
			dialog.find('input.time-of-day').hide().radio('check', dayMonthYear == 1 ? 'outer-day' : '');
			dialog.find('.day-of-month').onoff(dayMonthYear == 2);
			dialog.find('input.day-of-month').hide().radio('check', dayMonthYear == 2 ? 'outer-month' : '');
			dialog.find('.month-of-year').onoff(dayMonthYear == 3);
			dialog.find('input.month-of-year').hide().radio('check', dayMonthYear == 3 ? 'outer-year' : '');
		}
		
		/////////////////////////////////////////////
		$.fn.onoff = _onoff;
	}
	
	var buildWeeks = function(dialog) {
		var board = dialog.find('.times-board');
		var weeks = [2, 3, 4, 5, 6, 7, 1];
		var weekName = [TempoUtils.locale("mine.xinqiyi"),
		                TempoUtils.locale("mine.xinqier"), 
		                TempoUtils.locale("mine.xinqisan"),
		                TempoUtils.locale("mine.xinqisi"),
		                TempoUtils.locale("mine.xinqiwu"),
		                TempoUtils.locale("mine.xinqiliu"),
		                TempoUtils.locale("mine.xinqitian")
		                ];
		weeks.forEach(function(e, i) {
			var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
			$("<input ui-role='checkbox' name='dayofweek' type='checkbox'/>").val(e).appendTo(span);
			$("<label/>").text(weekName[i]).appendTo(span);
		});
		TempoUtils.parserUi(board, {});
	};
	
	var buildDays = function(dialog) {
		var board = dialog.find('.times-board');
		for(var i = 1; i <= 31; i++) {
			var span = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
			$("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
				.val(i)
				.addClass('day-of-month-' + i)
				.appendTo(span);
			$("<label/>").text(i + TempoUtils.locale("mine.hao")).appendTo(span);
		}
		var lastSpan = $("<span style='display: inline-block;padding-left: 15px;width: 105px;'></span>").appendTo(board);
		$("<input ui-role='checkbox' name='dayofmonth' type='checkbox'/>")
			.val("L")
			.addClass('day-of-month-L')
			.appendTo(lastSpan);
		$("<label/>").text(TempoUtils.locale("mine.zuihouyitian")).appendTo(lastSpan);
		TempoUtils.parserUi(board, {});
	}
	/**
	 * 保存调度信息
	 */
	var saveJobConfig = function(oldjob, isEdit){
		var that = this;
		if(!validateForm(this.jobDialog)){
			return;
		}
		//暂存流程参数
		saveFlowParam.apply(that);
		
		var job = {
				themeId : analyseId,
				trigger : {
				},
				publishFlowIds : []
		}
		if(isEdit){
			job.id = oldjob.id;
			job.jobId = oldjob.jobId;
			job.creator = oldjob.creator;
			job.trigger.id = oldjob.jobId;
		}
		//调度参数
		var triggerParam = {};
		var trigger = job.trigger;
		var publishFlowIds = [];
		//调度信息
		var jobconfig = that.jobDialog.find('#tempo-mine-flow-config').serializeArray();
		
		// 添加对复选框值的处理，转变为一个属性值
		$.each(jobconfig, function(index, item){
			if(!item.name.startsWith('flow_')){
				if(trigger[item.name]) {
					if(Array.isArray(trigger[item.name])) {
						trigger[item.name].push(item.value);
					} else {
						trigger[item.name] = [trigger[item.name], item.value];
					}
				} else {
					trigger[item.name] = item.value;
				}
			}
		});
		// 解决IE10下面选中保存不了问题
		var isChecked = that.jobDialog.find('input[name=retry]').is(':checked');
		if(!trigger.retry && isChecked) {
			trigger.retry = 'on';
		}
		//由于之前的界面改动，此处的优先级信息需要手动获取，wtf
		// 上面的注释不是我加的，我也不敢删除，所以就加了这句注释
		if(!trigger.priority) {
			var priority =  that.jobDialog.find('select[name="priority"]').val();
			trigger.priority = priority;
		}
		if((that.jobDialog.find('input[name=dayofweek]').length && !trigger['dayofweek']) 
				|| (that.jobDialog.find('input[name=dayofmonth]').length && !trigger['dayofmonth'])) {
			$("<div/>").alert({msg : TempoUtils.locale("mine.qingxuanzeyunxingshijian"), height : 180});
			return false;
		}
		// 处理数组类型值，转换为逗号分割的字符串
		Array.isArray(trigger['dayofweek']) && (trigger['rundate'] = trigger['dayofweek'].join(','));
		Array.isArray(trigger['dayofmonth']) && (trigger['rundate'] = trigger['dayofmonth'].join(','));
		trigger['dayofweek']  && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofweek']);
		trigger['dayofmonth'] && !trigger['rundate'] && (trigger['rundate'] = trigger['dayofmonth']);
		delete trigger['dayofweek'];
		delete trigger['dayofmonth'];
		console.log(JSON.stringify(trigger))
		trigger.interval = Number(trigger.interval);
		if(trigger.retryNum) trigger.retryNum = Number(trigger.retryNum);
		//引用流程信息
		var relatedFlows = that.jobDialog.find('#selectFlowTable').find('tr');
		var relatedFlow = [];
		relatedFlows.each(function(i){
			 var flows = $(this).find('select').serializeArray();
			 var rflowObj = {};
			 $.each( flows, function(index, item){
				if($.inArray(item.value, publishFlowIds) == -1){
					if(item.value){
						publishFlowIds.push(item.value);
					}
				}
				if(item.value){
					rflowObj[item.name] = item.value;
				}
			 });
			 if(!$.isEmptyObject(rflowObj)){
				 relatedFlow.push(rflowObj);
			 }
		});
		
		triggerParam.flowsInJob = relatedFlow;
		
		if(publishFlowIds.length > 0){
			if(publishFlowIds.length == 1){
				job.publishFlowIds = publishFlowIds[0];
			}else{
				job.publishFlowIds = publishFlowIds.join(',');
			}
		}else{
			$("<div/>").alert({msg : TempoUtils.locale("mine.publish-job-none"), height : 180});
			return;
		}
		var process = $("<div/>").tempoprogressbar();

		//流程配置参数
		triggerParam.flowsParam = that.flowsParam;
		job.trigger.param = JSON.stringify(triggerParam);
		var url = isEdit ? contextPath + '/api/ai/mine/publish/editJob' : contextPath + '/api/ai/mine/publish/saveJob';
		$.ajax({
			url : url,
			type : 'post',
			data : JSON.stringify(job),
			contentType : 'application/json',
			success : function(obj) {
				process.tempoprogressbar("destroy");
				if (obj && obj.status) {
					$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
					that.jobDialog.dialog("destroy");
				} else {
					$("<div/>").alert({msg : TempoUtils.locale("mine.publish-savefailed") + obj.error, height : 180, width: 400});
				}
			},
			error:function(data){
				process.tempoprogressbar("destroy");
			}
		});
	}
	
	/**
	 * 暂存流程参数
	 */
	var saveFlowParam = function(){
		var that = this;
		var paramsTable = that.jobDialog.find('#flowParamsContainer table');
		var currentFlow = paramsTable.attr('flowId');
		if(currentFlow){
			var currentFlowParams = []
			var paramsLine = paramsTable.find('tbody tr');
			paramsLine.each(function(i){
				var paramName = $(this).find('input.flow_paramname').val();
				var paramType = $(this).find('input.flow_paramtype').val();
				var paramId = $(this).find('input.flow_paramid').val();
				var paramValue = $(this).find('select.flow_paramvalue').selectmenu('getValue');
				var param = {};
				param.paramName = paramName;
				param.paramValue = paramValue;
				param.paramId = paramId;
				param.paramType = paramType;
				if(!$.isEmptyObject(param)){
					currentFlowParams.push(param);
				}
			});
			that.flowsParam[currentFlow] = currentFlowParams;
		}
	}
	
	/**
	 * 新增调度对话框
	 */
	var initJobLayout = function(job){
		var that = this;
		var dialog = that.jobDialog;
		initFormData.apply(that, [job]);
		initSelectFlowTable.apply(that, job? [job] : null);
	}
	
	/**
	 * 新增流程选择
	 */
	var addNewFlowRow = function(target, data){
		var that = this;
		var dialog = that.jobDialog;
		var allFlows = dialog.find('#selectFlowTable tbody tr');
		var fids = [];
		//上级流程待选
		var fEles = [];
		allFlows.each(function(i){
			var fele = $(this).find('td:first select')
			var fid = fele.val();
			if(fids.indexOf(fid) == -1){
				fids.push(fid);
				fEles.push(fele.find('option[value="' + fid + '"]').clone());
			}
		});
		
		//本级流程
		var addContent = $(target).parents('tr.firstSeletedFlow').clone();
		var tds = addContent.find('td');
		var firstFlows = tds.first().find('select option');
		if(firstFlows.length == fids.length){
			return;
		}
		var firstFlowEles = []
		firstFlows.each(function(i){
			var fid = $(this).attr('value');
			if(fids.indexOf(fid) == -1){
				firstFlowEles.push($(this).clone());
			}
		});
		var cursel = tds.first().find('select').empty().append(firstFlowEles).clone();
		cursel.attr("id",TempoUtils.uuid());
		tds.first().empty().append(cursel);
		
		tds.last().empty();
		var deleteFlowRow = $('<span>')
			.addClass('job-flow-deletebtn ui-icon ui-icon-minus')
			.text(TempoUtils.locale('mine.publish-btn-delete'))
			.bind('click', [dialog], removeRow);
		tds.last().append(deleteFlowRow);
		var psel = tds.eq(1).find('select').empty().clone();
		psel.attr("id",TempoUtils.uuid());
		tds.eq(1).empty().append(psel.append(fEles));
		dialog.find('#selectFlowTable').append(addContent);
		addContent.find('select').selectmenu({
			width : 140,
			labelForTitle: true
		});
		
		addContent.find('select').each(function(){
			$(this).selectmenu('option','change', function(){
				flowSelectHandler.apply(that,[this]);
				var opVal = this.val();
				dialog.find("#publish-mine-job-param-label").text(flowInfo[opVal]+'-'+paramLabel);
				$(this).parents('tr').nextAll('tr').remove();
			});
		});
		addContent.find('select').parent().each(function(){
			$(this).unbind("click").bind("click", function(){
				var opVal = $(this).find('select').val();
				dialog.find("#publish-mine-job-param-label").text(flowInfo[opVal]+'-'+paramLabel);
				flowSelectHandler.apply(that, [$(this).find('select'), false]);
			})
		});
		// 对新加载的第一个有参数和数据源的流程进行加载
		if(data){
			addContent.find('select:first').val(data.flow_current).selectmenu('refresh');
			addContent.find('select').eq(1).val(data.flow_parent).selectmenu('refresh');
		} else {
			var opVal = dialog.find('.flow-select:first').val();
			dialog.find("#publish-mine-job-param-label").text(flowInfo[opVal]+'-'+paramLabel);
			flowSelectHandler.apply(that, [addContent.find('.flow-select:first'), false]);
		}
	}
	
	
	
	var initSelectFlowTable = function(job){
		var that = this;
		var dialog = that.jobDialog;
		var flows = $('#mine-published-grid').jqGrid('getRowData');
		//待编辑数据
		var flowParams = job ? JSON.parse(job.trigger.param) : null;
		//初始化流程选择下拉框
		var html = '';
		var flowTableTr = dialog.find('#flowTableTr');
		var paramTableTr = dialog.find('#paramTableTr');
		if(flows && flows.length > 0){
			flowTableTr.show();
			for (var i = 0; i < flows.length; i++) {
				var flow = flows[i];
				var name = flow.name;
				var id = flow.id;
				if(i == 0){
					dialog.find('#setFlowParamTable').attr('flowId', id);
				}
				html += '<option value="' + id + '">' + name + '</option>';
				flowInfo[id] = name;
			}
		}else{
			flowTableTr.empty().hide();
			paramTableTr.empty().hide();
		}
		//第一行
		dialog.find('.flow-select').each(function(){
			$(this).html(html);
			$(this).selectmenu({
				width : 140,
				labelForTitle: true
			});
		});
		dialog.find('.flow_parent').each(function(){
			$(this).selectmenu({
				width : 140,
				labelForTitle: true
			});
		})
		
		
		if(flowParams){
			var selectedFlows = flowParams.flowsInJob;
			var flowParam = flowParams.flowsParam;
			that.flowsParam = flowParams.flowsParam;
			if(selectedFlows && selectedFlows.length > 0){
				for (var i = 0; i < selectedFlows.length; i++) {
					if(i==0){
						dialog.find('.flow-select:first').val(selectedFlows[i].flow_current).selectmenu('refresh');
					}else{
						addNewFlowRow.apply(that,[dialog.find('#selectFlowTable .job-flow-addbtn'), selectedFlows[i]])
					}
				}
			}
		}
		flowSelectHandler.apply(that,[dialog.find('.flow-select:first'), true]);
		var opVal = dialog.find('.flow-select:first').val();
		dialog.find("#publish-mine-job-param-label").text(flowInfo[opVal]+'-'+paramLabel);

		dialog.find('.flow-select').each(function(){
			$(this).selectmenu('option','change', function(){
				var opVal = $(this).val();
				dialog.find("#publish-mine-job-param-label").text(flowInfo[opVal]+'-'+paramLabel);
				flowSelectHandler.apply(that,[this]);
				$(this).parents('tr').nextAll('tr').remove();
			});
		});
		
		dialog.find('#flowOrderContainer').find('select').parent().each(function(){
			$(this).unbind("click").bind("click", function(){
				var opVal = $(this).find('.flow-select').val();
				dialog.find("#publish-mine-job-param-label").text(flowInfo[opVal]+'-'+paramLabel);
				flowSelectHandler.apply(that,[$(this).find('.flow-select')]);
			})
		});
		
		if(flows && flows.length > 1){
			dialog.find('#selectFlowTable .job-flow-addbtn').show();
			//新增一行flow选择
			dialog.find('#selectFlowTable .job-flow-addbtn').unbind('click').bind('click', function(){
				addNewFlowRow.apply(that,[this])
			});
		}else{
			//如果只有一个流程则隐藏新增按钮
			dialog.find('#selectFlowTable .job-flow-addbtn').hide();
		}
	}
	
	/**
	 * 流程选择事件处理
	 */
	var flowSelectHandler = function(target, isFirst){
		var that = this;
		var dialog = that.jobDialog;
		//先保存之前的流程参数配置
		if(!isFirst){
			saveFlowParam.apply(that);
		}
		dialog.find('#flowParamsContainer').hide();

		var flowid = $(target).val();
		var params = that.flowsParam[flowid];
		var grid = dialog.find('#setFlowParamTable').attr('flowId', $(target).val());
		grid.find('tbody').empty();
		var getFlowParams = function(type, paramValueInput, value, nodeType){
			var pss = [];
			if(type == 'datasource'){
				var process = $("<div/>").tempoprogressbar();
				$.ajax({
					url:contextPath + '/api/ai/node/io/list-datasources',
				    type:'post',
				    success:function(rs) {
				    	process.tempoprogressbar("destroy");
				    	var data = rs.data;
						var itemHtml = [];
						for(var i =0;i<data.length;i++){
							var dataItem = data[i];
							// 屏蔽模型数据源、presto数据源、impala数据源
							if (nodeType == 'readrdbms') {
								if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1) {
									continue;
								}
							}
							if (nodeType == 'writerdbms') {
								if (!dataItem.type || TempoMineUtils.inputSupportType.indexOf(dataItem.type) == -1 || (dataItem.purpose && dataItem.purpose != "1")) {
									continue;
								}
							}

							if (nodeType == 'readhive') {
								if (dataItem.type != 'hive') {
									continue;
								}
							}
							if(nodeType == 'writehive'){
								if('hive' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")){
									continue;
								}
							}
							if (nodeType == "readinfluxdb") {
								if (!(dataItem.type == "influxdb" || dataItem.type == "influxdb2")) {
									continue;
								}
							}
							if( nodeType == "readiotdb"){
								if (dataItem.type != 'iotdb') {
									continue;
								}
							}
							if( nodeType == "writeiotdb"){
								//不是iotdb  或者不能写入
								if ('iotdb' != dataItem.type  || (dataItem.purpose && dataItem.purpose != "1")) {
									continue;
								}
							}
							
							itemHtml.push('<option value="' + dataItem.code + '">' + dataItem.name + '</option>')
						}
						var html = itemHtml.join('');
						paramValueInput.html(html);
						paramValueInput.selectmenu({
							editable : false,
							width : 150,
							labelForTitle: true
						}).selectmenu('setValue', value).selectmenu('refresh');
				    }
				});
			}else{
				var items = TempoMineUtils.getConstFlowParams();
				if(items){
					for(name in items){
						pss.push('<option value="' + name + '">' + items[name] + '</option>')
					}
				}
				var html = pss.join('');
				paramValueInput.html(html);
				paramValueInput.selectmenu({
					editable : true,
					width : 150,
					labelForTitle: true
				}).selectmenu('setValue', value);
			}
			
		}
		var initParamGrid = function(ps){
			dialog.find('#flowParamsContainer').show();
			for (var i = 0; i < ps.length; i++) {
				var tr = $('<tr>').appendTo(grid);
				var p = ps[i];
				var paramName = p.paramName;
				var paramValue = p.paramValue;
				var paramType = p.paramType;
				var paramId = p.paramId;
				var nodeType = p.nodeType;
				var paramNameTd = $('<td>').appendTo(tr);
				var paramNameInput = $('<input name="paramName">').addClass('flow_paramname').appendTo(paramNameTd).val(paramName);
				var paramTypeInput = $('<input name="paramType" type="hidden">').addClass('flow_paramtype').appendTo(paramNameTd).val(paramType);
				var paramTypeInput = $('<input name="paramId" type="hidden">').addClass('flow_paramid').appendTo(paramNameTd).val(paramId);
				var paramValueTd = $('<td>').appendTo(tr);
				var paramValueInput = $('<select name="paramValue">').addClass('flow_paramvalue').appendTo(paramValueTd);
				paramNameInput.validatebox({width : 100, readonly : true});

				paramNameInput.attr('title', paramName);
				getFlowParams(paramType, paramValueInput, paramValue,nodeType);
			}
		};
		
		if(!params || params.length == 0){
			$.ajax({
				url : contextPath+"/api/ai/mine/publish/getPublishFlowParams/" + flowid,
				type : 'post',
				success : function(result){
					if(result && result.length > 0){
						initParamGrid(result);
					}
				}
			})
		}else{
			initParamGrid(params);
		}
		
	}
	
	/**
	 * 删除表格一行
	 */
	var removeRow = function(evt){
		var dialog = evt.data[0];
		var tr = $(this).parent('td').parent('tr');
		var v = tr.find('select[name=flow_current]').selectmenu('getValue');
		var table = dialog.find('table.mtable[flowid=' + v + ']');
		if(table && table.length) {
			table.find('tbody').remove();
			dialog.find('#flowParamsContainer').hide();
		}
		tr.remove();
	}
	
	
	/**
	 * 调度列表事件
	 */
	var bindJobGridEvent = function(){
		var that = this;
		var grid = $('#mine-opt-job-grid');

		grid.find(".edit-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			editJob.apply(that, [row]);
		});
		grid.find(".run-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			runJob(row);
		});
		grid.find(".stop-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			stopJob(row, function() {
				 grid.jqGrid().trigger("reloadGrid");
			});
		});
		grid.find(".del-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			deleteJob(row);
		});
		
		grid.find(".log-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var log = $(e.target).attr('logid');
			var runResult = $(e.target).attr('runResult');
			var row = grid.jqGrid("getRowData", rowid);
			downloadLog(row.id, log, runResult);
		});
		grid.find(".viewlog").each(function(){
			var rowid = $(this).attr('rowid');
			var row = null;
			var rows = grid.data('rows');
			if(rows && rows.length > 0){
				for (var m = 0; m < rows.length; m++) {
					if(rowid == rows[m].id){
						row = rows[m];
					}
				}
			}
			var logs = row.logs;
			var content;
			if(logs && logs.length > 0){
				var logele = $('<ul>').css({
					'list-style-type' : 'none'
				});
				for (var i = 0; i < logs.length; i++) {
					var log = logs[i];
					var date = new Date(parseFloat(log.runTime));
					var runResult = log.runResult;
					var icon = "ui-icon ui-icon-document";
					if (runResult != null) {
						if (runResult == 0) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-errorprompt";
						} else if (runResult == 1) {
							icon = "ui-icon tempo-ui-icon tempo-ui-icon-no-mutual tempo-ui-icon-red-circle-check-thin";
						}
					}
					var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
					var liele = $('<li class="logitem">').attr('jobid', rowid).attr('logid', log.id).attr('runResult', log.runResult).attr('name', logName);
					var liicon = $("<span>").addClass(icon).appendTo(liele);
					var lilabel = $("<label>").text(logName).appendTo(liele);
					logele.append(liele);
				}
				content = $('<div>').append(logele).html();
			}
			var height = 'auto';
			if(logs && logs.length > 0 && logs.length > 5){
				height = 100;
			} else if(logs && logs.length > 0 && logs.length <= 5) {
				height = logs.length * 20;
			}
			$(this).webuiPopover({
				trigger : 'hover',
				title : '',
				cache : false,
				placement : 'right',
				width : 195,
				height: height,
				closeable : false,
				arrow : true,
				content : content
			})
			$(this).on('shown.webui.popover', function(){
				$('.logitem').each(function(index, domEle){
					$(domEle).off('click').on('click',function(){
						var jobid = $(this).attr('jobid');
						var logid = $(this).attr('logid');
						var runResult = $(this).attr('runResult');
						var name = $(this).attr('name');
						downloadLog(jobid, logid, name, runResult);
					})
				});
			});
		});
	}
	
	/**
	 * 下载任务日志
	 */
	var downloadLog = function(id, log, name,runResult){
		TempoUtils.downLoadFile({
			url: contextPath + "/api/ai/mine/publish/downloadJobLog",
			data : {
				id : id,
				name : name,
				log : log,
				runResult : runResult
			}
		});
	}
	/**
	 * 初始化调度列表
	 */
	this.initJobGrid = function() {
		var that = this;
		var height = $('#publish-mine-config').height()-155;
		var width = $('#publish-mine-config').width()-30;
		that.grid = $('#mine-opt-job-grid').datagrid({
			datatype : "json",
			url : contextPath + '/api/ai/mine/publish/listJob?time=' + new Date().getTime(),
			postData : {themeId : analyseId},
			height : height,
			width : width,
			fit:true,
			rownumbers : true,
			mtype : 'POST',
			autowidth:true,
			rownumbers : true,
			shrinkToFit : true, 
			viewrecords : true,
			striped : true,
			colNames : [ 'id', 
			             'jobId',
			             'triggertype',
			             'priority',
			             'starttime',
			             'endtime',
			             'param',
			             'logs',
			             TempoUtils.locale("mine.publish-mine-job-grid-col-name"),//'任务名称'
			             /*TempoUtils.locale("mine.publish-mine-job-grid-col-priority"),*///'优先级'
			             'creator',
			             TempoUtils.locale("mine.publish-mine-job-grid-col-creator"),//'创建者'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-lasttime"),//'上次执行时间'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-lastcosttime"),//'上一次执行耗时'
			             TempoUtils.locale("mine.shangcizhixingjieguo"),
			             TempoUtils.locale("mine.publish-mine-job-grid-col-nexttime"),//'下一次执行时间'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-relatedflow"),//'涉及流程'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-log"),//'日志'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-status") ,//'状态'
			             TempoUtils.locale("mine.zhixingqingkuang"), 
			             TempoUtils.locale("mine.publish-mine-job-grid-col-opt")
			             ],//'操作'
			colModel : [{
						name : 'id',
						index : 'id',
						hidden : true
					},{
						name : 'jobId',
						index : 'jobId',
						hidden : true
					},{
						name : 'trigger.triggertype',
						index : 'trigger.triggertype',
						hidden : true
					},{
						name : 'trigger.priority',
						index : 'trigger.priority',
						hidden : true
					},{
						name : 'trigger.starttime',
						index : 'trigger.starttime',
						hidden : true
					},{
						name : 'trigger.endtime',
						index : 'trigger.endtime',
						hidden : true
					},{
						name : 'trigger.param',
						index : 'trigger.param',
						hidden : true
					},{
						name : 'logs',
						index : 'logs',
						hidden : true
					},{
						name : 'trigger.name',
						index : 'trigger.name',
						resizable:false,
						sortable : false
					},/*{
						name : '',
						index : '',
						align : 'center',
						width : 50,
						sortable:false,
						formatter : function(val, grid, rows, state) {
							var obj = rows.trigger.priority;
							if(obj == '1'){
								return  TempoUtils.locale("mine.publish-mine-job-priority-high");
							}else if(obj == '2'){
								return  TempoUtils.locale("mine.publish-mine-job-priority-middle");
							}else if(obj == '3'){
								return  TempoUtils.locale("mine.publish-mine-job-priority-low");
							}
							return "";
						}
					},*/{
						name : 'creator',
						index : 'creator',
						hidden : true
					},{
						name : 'creatorName',
						index : 'creatorName',
						width : 80,
						sortable:false
					},{
						name : 'trigger.prevtime',
						index : 'trigger.prevtime',
						align : 'center',
						resizable:false,
						sortable : false,
						formatter : function(obj, grid, rows, state) {
							if(obj && rows.cost) {
								return obj;
							} else {
								return '';
							}
						}
					},{
						name : 'cost',
						index : 'cost',
						align : 'center',
						width : 85,
						resizable:false,
						sortable : false,
						formatter : function(obj, grid, rows, state) {
							if(rows.cost > 0){
								return rows.cost + TempoUtils.locale("mine.publish-mine-job-exe-second");
							}
							return "";
						}
					},{
						name : 'result',
						index : 'result',
						align : 'center',
						width : 85,
						resizable:false,
						sortable : false,
						formatter : function(obj, grid, rows, state) {
							if(obj == 0 && rows.trigger && rows.trigger.prevtime && rows.cost) {
								return TempoUtils.locale("mine.shibai");
							} else if(obj == 1) {
								return TempoUtils.locale("mine.chenggong");
							}
							return "";
						}
					},{
						name : 'trigger.nexttime',
						index : 'trigger.nexttime',
						align : 'center',
						align : 'center',
						resizable:false,
						sortable : false,
						formatter : function(obj, grid, rows, state) {
							if(rows.trigger.status == "PAUSED") {
								return '--';
							} else {
								return obj || '--';
							}
						}
					},{
						name : 'publishFlowIds',
						index : 'publishFlowIds',
						resizable:false,
						sortable : false,
						width : 100,
						formatter : function(obj, grid, rows, state) {
							var flows = $('#mine-published-grid').jqGrid('getRowData');
							var html = [];
							if(flows && flows.length > 0){
								for (var i = 0; i < flows.length; i++) {
									var flow = flows[i];
									var id = flow.id;
									if(obj.indexOf(id) > -1){
										html.push(flow.name);
									}
								}
							}
							return html.join(';') 
						}
					},{
						name : '',
						index : '',
						sortable : false,
						align : 'left',
						width : 40,
						formatter : function(obj, grid, rows, state) {
							var logs = rows.logs;
							if(logs && logs.length > 0){
								return "<a href='javascript:;void(0)' rowid='" + rows.id + "' class='viewlog'>" + TempoUtils.locale("mine.publish-mine-job-log-view") + "</a>";
							}
							return '';
						}
					},{
						name : 'trigger.state',
						index : 'trigger.state',
						sortable : false,
						align : 'center',
						width : 70, 
						formatter : function(obj, grid, rows, state) {
							if(rows.trigger.status == "PAUSED"){
								return TempoUtils.locale("mine.publish-btn-pause");
							} else if(rows.trigger.status == "COMPLETE"){
								return TempoUtils.locale("mine.jiesu");
							} else {
								return TempoUtils.locale("mine.yunxing");
							}	
						}
					},{
						name : 'trigger.status',
						index : 'trigger.status',
						sortable : false,
						width : 170, 
						formatter : function(obj, grid, rows, state) {
							var success = rows.successCount || 0;
							var fail = rows.failedCount || 0;
							return  TempoUtils.locale("mine.publish-mine-job-exe-success") +"<span style='color:green'>" + success + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time")+ "　" + TempoUtils.locale("mine.publish-mine-job-exe-fail") + "<span style='color:red'>" + fail + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time");
						}
					},{
						sortable : false,
						width : 180,
						align : 'center',
						buttons:[{
							id : "edit",
							icon:"ui-icon tempo-ui-icon tempo-ui-icon-edit",
							title: TempoUtils.locale("mine.publish-btn-edit"),
							click:function(e,dt){	     
								var rowid = dt.rowId;
								var row = dt.rowData;
								editJob.apply(that, [row]);
							}
						},{
							id : "kill",
							icon:"ui-icon tempo-ui-icon tempo-ui-icon-kill",
							title: TempoUtils.locale("mine.publish-btn-stop"),
							click:function(e,dt){	     
								var rowid = dt.rowId;
								var row = dt.rowData;
								stopJob(row, function() {
									that.grid.jqGrid().trigger("reloadGrid");
								});
							}
						},{
							id : "pause",
							title: TempoUtils.locale("mine.publish-btn-pause"),
							beforeAdd : function(rowId,rowData, btn){
								if(rowData.trigger.status == "COMPLETE"){
									btn.icon = "ui-icon tempo-ui-icon tempo-ui-icon-resume";
									btn.title = TempoUtils.locale("mine.publish-btn-start");
								} else if(rowData.trigger.status == "PAUSED"){
									btn.icon = "ui-icon tempo-ui-icon tempo-ui-icon-resume";
									btn.title = TempoUtils.locale("mine.publish-btn-start");
								} else {
									btn.icon = "ui-icon tempo-ui-icon tempo-ui-icon-pause";
									btn.title = TempoUtils.locale("mine.publish-btn-pause");
								}
							},
							click:function(e,dt){
								var rowid = dt.rowId;
								var row = dt.rowData;
								pauseJob(row);
							}
						},{
							id : "manual",
							icon:"ui-icon tempo-ui-icon tempo-ui-icon-manual",
							title: TempoUtils.locale("mine.shoudongzhixing"),
							click:function(e,dt){	     
								var rowid = dt.rowId;
								var row = dt.rowData;
								manualJob(row);
							}
						},{
							id : "delete",
							icon:"ui-icon tempo-ui-icon tempo-ui-icon-delete",
							title: TempoUtils.locale("mine.publish-btn-delete"),
							click:function(e,dt){
								var rowid = dt.rowId;
								var row = dt.rowData;
								deleteJob(row);
							}
						}]
					}
				],
			loadComplete : function(datas){
				var rows = datas.rows;
				$(this).data('rows', rows);
				bindJobGridEvent.apply(that);
				var arr = rows.filter(function(e) {
					if((DataObserveCenter.isObserve(e.id) && e.result != -1)
							|| (DataObserveCenter.isStop(e.id) && e.result == -1)) {
						return true;
					} else {
						DataObserveCenter.remove(e.id);
						return false;
					}
				});
				if(arr.length) {
					setTimeout(function(){
						that.grid.jqGrid().trigger("reloadGrid");
					}, 1000);
				}
			},
			pagination : true
		});
	}
	
	/**
	 * 校验表单
	 */
	var validateForm = function(dialog){
		var v = dialog.find('form').formValidate();
		var jobconfig = TempoUtils.getRecord(dialog.find('form'));
		return v && (function(){
			console.log(jobconfig);
			if(jobconfig.starttime && jobconfig.endtime) {
				var s = new Date(jobconfig.starttime);
				var e = new Date(jobconfig.endtime);
				if(s.getTime() > e.getTime()) {
					$("<div/>").alert({msg : TempoUtils.locale("mine.shengxiaoshijianerror"), height : 180});
					return false;
				}
			}
			if(jobconfig.stime && jobconfig.etime) {
				if(jobconfig.stime >= jobconfig.etime && jobconfig.runType == 'inner-day') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.kaishishijianerror"), height : 180});
					return false;
				}
				if(jobconfig.stime == jobconfig.etime && jobconfig.runType == 'outer-day') {
					$("<div/>").alert({msg : TempoUtils.locale("mine.schedule-stime-not-equls-etime"), height : 180});
					return false;
				}
			}
			var flowCurrentId = jobconfig.flow_current;
			var flag = true;
			$.ajax({
				url:contextPath+"/api/ai/mine/publish/getFlowGraphData",
				data:{
					id : flowCurrentId
				},
				dataType:'json',
				type:'post',
				async:false,
				success:function(result){
					var nodeTypes = ['readkafka'];
					if(result){
						var flowJSON = JSON.parse(result);
						if (!$.isEmptyObject(flowJSON)){
							var children = flowJSON.children;
							if (children && children.length > 0) {
								for (var i = 0 ; i < children.length; i++) {
									var childNode = children[i];
									if (nodeTypes.indexOf(childNode.nodeType) > -1) {
										flag = false;
										break;
									}
								}
							}
						}
					}
				}
			});
			if (!flag) {
				$("<div/>").alert({msg : TempoUtils.locale("mine.schedulenotsupportkafka"), height : 180});
				return false;
			}
			return true;
		})();
	}
		
	
	
	this.initOrrefresh = function(){
		var that = this;
		$('.publish_tab').height($('#publish-mine-config').height()-98)
		if(!this.grid){
			this.initJobGrid();
			$('#jobsearcher').searchbar({
				placeholder:TempoUtils.locale("mine.searchjobname"),
				onSearch : function(text){
					var name = text.trim();
					if(name && name.length > 0){
						//拼接出所有的模糊匹配涉及流程的id
						var flows = $('#mine-published-grid').jqGrid('getRowData');
						var flowids = [];
						if(flows && flows.length > 0){
							for (var i = 0; i < flows.length; i++) {
								var flow = flows[i];
								if(flow.name.indexOf(name) > -1){
									flowids.push(flow.id);
								}
								
							}
						}
						that.grid.jqGrid('setGridParam',
								{
									postData : {
										name : name,
										flowids:flowids.join(",")
									}
								}).trigger("reloadGrid");
					}else{
						that.grid.jqGrid('setGridParam',
								{
									postData : {themeId : analyseId, name : null}
								}).trigger("reloadGrid");
					}
				}
			});
			$('#mine-opt-job-newbtn').button({
				useRadius : true,
				label : TempoUtils.locale('mine.publish-btn-new'),
				click : function(){
					newJob.apply(that);
				}
			});
		}else{
			that.grid.jqGrid('setGridParam',
					{
						postData : {themeId : analyseId, name : null}
					}).trigger("reloadGrid");
		}
	}
	
}